<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wx:msgTemplate:edit']"
        >配置数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wx:msgTemplate:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wx:msgTemplate:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="templateMsgTaskHandle()"
          :disabled="single"
          v-hasPermi="['wx:msgTemplate:save']"
        >推送消息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="syncWxTemplate()"
          :disabled="synchonizingWxTemplate"
          v-hasPermi="['wx:msgTemplate:save']"
        >{{synchonizingWxTemplate?'同步中...':'同步公众号模板'}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="msgTemplateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板ID" align="center" prop="templateId" />
      <el-table-column label="模版名称" align="center" prop="name" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="模板内容" align="center" prop="content"  show-overflow-tooltip/>
      <el-table-column label="链接" align="center" prop="url" show-overflow-tooltip/>
      <el-table-column label="是否有效" align="center" prop="status">
        <span slot-scope="scope">{{scope.row.status?"是":"否"}}</span>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wx:msgTemplate:edit']"
          >配置数据</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wx:msgTemplate:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消息模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接" />
        </el-form-item>
        <el-form-item label="小程序appid" prop="miniprogram.appid">
          <el-input v-model="form.miniprogram.appid" placeholder="小程序appid"></el-input>
        </el-form-item>
        <el-form-item label="小程序路径" prop="miniprogram.pagePath">
          <el-input v-model="form.miniprogram.pagePath" placeholder="小程序pagePath"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="模版名称" prop="name">
              <el-input v-model="form.name" placeholder="模版名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效" prop="status">
              <el-switch v-model="form.status" placeholder="是否有效" :active-value="true" :inactive-value="false"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-group-area">
          <el-form-item  class="form-group-title">消息填充数据，请对照模板内容填写</el-form-item>
          <el-form-item>
            <el-input type="textarea" disabled autosize v-model="form.content" placeholder="模版"></el-input>
          </el-form-item>
          <el-row v-for="(item,index) in form.data" :key="item.name">
            <el-col :span="16">
              <el-form-item :label="item.name" :prop="'data.'+index+'.value'" :rules="[{required: true,message: '填充内容不得为空', trigger: 'blur' }]">
                <el-input type="textarea" autosize rows="1" v-model="item.value" placeholder="填充内容"  ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="颜色" >
                <el-input type="color" v-model="item.color" placeholder="颜色"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <template-msg-task v-if="templateMsgTaskVisible" ref="templateMsgTask"></template-msg-task>
  </div>
</template>

<script>
import { listMsgTemplate, getMsgTemplate, delMsgTemplate, addMsgTemplate, updateMsgTemplate, syncWxTemplate } from "@/api/wx/msgTemplate";
import TemplateMsgTask from '@/components/template-msg-task'

export default {
  name: "MsgTemplate",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      dataListSelections: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息模板表格数据
      msgTemplateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appid: undefined,
        templateId: undefined,
        name: undefined,
        title: undefined,
        content: undefined,
        data: undefined,
        url: undefined,
        miniprogram: undefined,
        status: undefined,
      },
      templateMsgTaskVisible:false,
      synchonizingWxTemplate:false,
      // 表单参数
      form: {
        templateId: '',
        title: '',
        data: [],
        url: '',
        miniprogram:{appid:'',pagePath:''},
        content: '',
        status: true,
        name: ''
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模版名称不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ]
      }
    };
  },
  components: {
    TemplateMsgTask
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询消息模板列表 */
    getList() {
      this.loading = true;
      listMsgTemplate(this.queryParams).then(response => {
        this.msgTemplateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        appid: undefined,
        templateId: undefined,
        name: undefined,
        title: undefined,
        content: undefined,
        data: [],
        url: undefined,
        miniprogram:{appid:'',pagePath:''},
        status: true,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.dataListSelections = selection
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMsgTemplate(id).then(response => {
        this.loading = false;
        this.transformTemplate(response.data);
        this.open = true;
        this.title = "修改消息模板";
      });
    },
    /**
     * 根据content信息展开data配置项(content为微信公众平台后台配置的模板)
     * 如content='{{first.DATA}} ↵商品名称：{{keyword1.DATA}} ↵购买时间：{{keyword2.DATA}} ↵{{remark.DATA}}'
     * 则生成data=[{name:'first',value:'',color:''},{name:'first',value:'',color:''},{name:'first',value:'',color:''}]
     * 展示表单让管理员给对应的字段填充内容
     */
    transformTemplate(template){
      if(!template.miniprogram)template.miniprogram={appid:'',pagePath:''}
      if(template.data instanceof Array) {//已经配置过了，直接读取
        this.form =  template
        return
      }

      template.data=[]
      let keysArray = template.content.match(/\{\{(\w*)\.DATA\}\}/g) || [] //示例： ["{{first.DATA}}", "{{keyword1.DATA}}", "{{keyword2.DATA}}", "{{remark.DATA}}"]
      keysArray.map(item=>{
        name = item.replace('{{','').replace('.DATA}}','')
        template.data.push({"name":name,"value":"",color:"#000000"})
      })
      this.form = template
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMsgTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMsgTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除消息模板编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delMsgTemplate(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wx/msgTemplate/export', {
        ...this.queryParams
      }, `msgTemplate_${new Date().getTime()}.xlsx`)
    },
    templateMsgTaskHandle(){
      this.templateMsgTaskVisible = true
      this.$nextTick(() => {
        this.$refs.templateMsgTask.init(this.dataListSelections[0])
      })
    },
    syncWxTemplate(){
      if(this.synchonizingWxTemplate)return
      this.synchonizingWxTemplate=true
      syncWxTemplate().then(response => {
        this.$message({
          message: '同步完成',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.getList()
          }
        })
      }).finally(() => {
        this.synchonizingWxTemplate=false;
      });
    }
  }
};
</script>
<style scoped>
  .form-group-area{
    border:1px dotted gray;
  }
  .form-group-title{
    color: gray;
    font-size: 12px;
  }
</style>
